package com.gamatechno.solodestination;


import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.gamatechno.adapter.CustomGridViewAdapter;
import com.gamatechno.adapter.CustomSubGridView;
import com.gamatechno.adapter.CustomSubGridView2;
import com.gamatechno.solodestination.model.AppPreferences;
import com.gamatechno.solodestination.model.HttpUtils;
import com.gamatechno.solodestination.model.Item;
import com.gamatechno.solodestination.model.Item2;
import com.gamatechno.solodestination.model.Kuliner;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("ValidFragment")
public class SubMenuFragment extends Fragment {
	AppPreferences _appPrefs;
	String tipe = "";
	public String judul;
	ArrayList<Item2> gridArray = new ArrayList<Item2>();
	int tipe_url = 0;

	public SubMenuFragment(String tipes) {
		tipe = tipes;
	}

	String[] Karisidenan = { "Surakarta", "Boyolali", "Klaten", "Sragen",
			"Kartasura" };

	GridView grid;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		_appPrefs = new AppPreferences(getActivity());
		View rootView = inflater.inflate(R.layout.fragment_submenu, container,
				false);

		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		TextView SubTitle = (TextView) getActivity()
				.findViewById(R.id.titleSub);
		Spinner spin = (Spinner) getActivity().findViewById(R.id.spinner);
		ArrayAdapter<String> spinAdapter = new ArrayAdapter<String>(
				getActivity(), R.drawable.spinner_item, Karisidenan);
		spin.setAdapter(spinAdapter);

		SubTitle.setText(tipe);

		if (tipe.equals("Kuliner")) {

			new GetKuliner().execute();
		}
		
		// setKuliner();

		LinearLayout filter = (LinearLayout) getActivity().findViewById(
				R.id.filter);
		filter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Dialog filterdialog = filter();
				filterdialog.show();
			}
		});

		LinearLayout sort = (LinearLayout) getActivity()
				.findViewById(R.id.sort);
		sort.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Dialog filterdialog = sort();
				filterdialog.show();

			}
		});
		
		spin.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				tipe_url=5+position;
				new GetKuliner().execute();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	private class GetKuliner extends AsyncTask<Void, Void, ArrayList<Kuliner>> {

		ProgressDialog dialog = new ProgressDialog(getActivity());

		protected void onPreExecute() {
			dialog.setMessage(" Loading... ");
			dialog.show();
		}
		
		@Override
		protected ArrayList<Kuliner> doInBackground(Void... params) {
			ArrayList<Kuliner> ark = new ArrayList<Kuliner>();

			String url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="
					+ _appPrefs.getBahasa() + "";
			switch (tipe_url) {
			case 1:
				url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="
						+ _appPrefs.getBahasa() + "&order=asc";

				break;
			case 2:
				url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="
						+ _appPrefs.getBahasa() + "&order=desc";
				break;
			case 3:
				url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="+ _appPrefs.getBahasa() + "&category=1";
				break;
			case 4:
				url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="+ _appPrefs.getBahasa() + "&category=2";
				break;
			case 5:
				url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="+ _appPrefs.getBahasa() + "&district="+(tipe_url-4);
				break;
				
			case 6:
				url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="+ _appPrefs.getBahasa() + "&district="+(tipe_url-4);
				break;
			case 7:
				url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="+ _appPrefs.getBahasa() + "&district="+(tipe_url-4);
				break;
			case 8:
				url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="+ _appPrefs.getBahasa() + "&district="+(tipe_url-4);
				break;
			case 9:
				url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="+ _appPrefs.getBahasa() + "&district="+(tipe_url-4);
				break;
				
			default:
				break;
			}

			Log.i("url", url);
			try {
				HttpUtils u = new HttpUtils();
				String a = u.getContents(url);
				Log.i("content", a);
				JSONObject obj = new JSONObject(a);
				Log.i("JSONObject content length", obj.length() + "");
				String jo = obj.get("result") + "";
				Log.i("isi result", jo + "");
				JSONArray ka = new JSONArray(jo);
				Log.i("result length", ka.length() + "");

				for (int i = 0; i < ka.length(); i++) {
					JSONObject ja = ka.getJSONObject(i);
					Kuliner kul = new Kuliner();
					kul.setName(ja.getString("name"));
					kul.setDescription(ja.getString("description"));
					kul.setLat(ja.getString("lat"));
					kul.setLng(ja.getString("lng"));
					kul.setImages("http://sms.gamatechno.com/solo_destination/files/kuliner/"
							+ ja.getString("images"));
					kul.setCategory(ja.getString("category"));
					kul.setDistrict_id(ja.getString("district_id"));
					kul.setDistrict(ja.getString("district"));
					kul.setImg("http://sms.gamatechno.com/solo_destination/files/kuliner/"
							+ ja.getString("images"));
					kul.setRating(ja.getString("rating"));
					kul.setComment(ja.getString("comment"));
					kul.setId_kuliner(ja.getString("id"));
					ark.add(kul);
					Log.i("i", ja.getString("name"));
					Log.i("i", ja.getString("description"));
					Log.i("i", ja.getString("lat"));
					Log.i("i", ja.getString("lng"));
					Log.i("i",
							"http://sms.gamatechno.com/solo_destination/files/kuliner/"
									+ ja.getString("images"));
					Log.i("i", ja.getString("category"));
					Log.i("i", ja.getString("district_id"));
					Log.i("i", ja.getString("district"));
					Log.i("i", ja.getString("rating"));
					Log.i("i", ja.getString("comment"));
					Log.i("i", ja.getString("id"));
					// gridArray.add(new Item(ja.getString("name"), "", "2",
					// "21"));

				}

			} catch (Exception e) {
				// e.printStackTrace();
				Log.i("i", e.toString());
			}

			return ark;

		}

		@Override
		protected void onPostExecute(ArrayList<Kuliner> result) {
			dialog.dismiss();
			setKuliner(result);
			// setSuhu();
			// super.onPostExecute(result);
		}
	}

	private class GetKulinerByFilter extends
			AsyncTask<Void, Void, ArrayList<Kuliner>> {
		
		
		ProgressDialog dialog = new ProgressDialog(getActivity());

		protected void onPreExecute() {
			dialog.setMessage(" Loading... ");
			dialog.show();
		}

		@Override
		protected ArrayList<Kuliner> doInBackground(Void... params) {
			ArrayList<Kuliner> ark = new ArrayList<Kuliner>();
			String url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=allkuliner&format=json&language="
					+ _appPrefs.getBahasa() + "&category=1";
			Log.i("url", url);
			try {
				HttpUtils u = new HttpUtils();
				String a = u.getContents(url);
				Log.i("content", a);
				JSONObject obj = new JSONObject(a);
				Log.i("JSONObject content length", obj.length() + "");
				String jo = obj.get("result") + "";
				Log.i("isi result", jo + "");
				JSONArray ka = new JSONArray(jo);
				Log.i("result length", ka.length() + "");

				for (int i = 0; i < ka.length(); i++) {
					JSONObject ja = ka.getJSONObject(i);
					Kuliner kul = new Kuliner();
					kul.setName(ja.getString("name"));
					kul.setDescription(ja.getString("description"));
					kul.setLat(ja.getString("lat"));
					kul.setLng(ja.getString("lng"));
					kul.setImages("http://sms.gamatechno.com/solo_destination/files/kuliner/"
							+ ja.getString("images"));
					kul.setCategory(ja.getString("category"));
					kul.setDistrict_id(ja.getString("district_id"));
					kul.setDistrict(ja.getString("district"));
					kul.setImg("http://sms.gamatechno.com/solo_destination/files/kuliner/"
							+ ja.getString("images"));
					kul.setRating(ja.getString("rating"));
					kul.setComment(ja.getString("comment"));
					kul.setId_kuliner(ja.getString("id"));
					ark.add(kul);
					Log.i("i", ja.getString("name"));
					Log.i("i", ja.getString("description"));
					Log.i("i", ja.getString("lat"));
					Log.i("i", ja.getString("lng"));
					Log.i("i",
							"http://sms.gamatechno.com/solo_destination/files/kuliner/"
									+ ja.getString("images"));
					Log.i("i", ja.getString("category"));
					Log.i("i", ja.getString("district_id"));
					Log.i("i", ja.getString("district"));
					Log.i("i", ja.getString("rating"));
					Log.i("i", ja.getString("comment"));
					Log.i("i", ja.getString("id"));
					// gridArray.add(new Item(ja.getString("name"), "", "2",
					// "21"));

				}

			} catch (Exception e) {
				// e.printStackTrace();
				Log.i("i", e.toString());
			}

			return ark;

		}

		@Override
		protected void onPostExecute(ArrayList<Kuliner> result) {
			dialog.dismiss();
			setKuliner(result);
			// setSuhu();
			// super.onPostExecute(result);
		}
	}

	public void setKuliner(final ArrayList<Kuliner> result) {

		gridArray.clear();
		for (Kuliner kuliner : result) {
			gridArray.add(new Item2(kuliner.getName(), "", kuliner.getRating(),
					kuliner.getComment(), kuliner.getImg()));
		}
		// gridArray.add(new Item("Contoh " + tipe + 1, "", "2", "21"));
		// gridArray.add(new Item("Contoh " + tipe + 2, "", "3.5", "66"));
		// gridArray.add(new Item("Contoh " + tipe + 3, "", "5", "21"));
		// gridArray.add(new Item("Contoh " + tipe + 4, "", "1.5", "15"));
		// gridArray.add(new Item("Contoh " + tipe + 5, "", "5", "21"));

		grid = (GridView) getActivity().findViewById(R.id.gridView1);
		CustomSubGridView2 CustomGrid = new CustomSubGridView2(getActivity(),
				R.layout.row_subgrid, gridArray, getActivity());
		grid.setAdapter(CustomGrid);
		grid.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Kuliner kul = result.get(position);
				Intent i = new Intent(getActivity(), SubKulinerActivity.class);
				judul = kul.getId_kuliner().toString();
				String lon = kul.getLng().toString();
				String lat = kul.getLat().toString();
				i.putExtra("judul", judul);
				i.putExtra("lat", lat);
				i.putExtra("lon", lon);
				startActivity(i);

				// judul = gridArray.get(position).getTitle();
				Log.d("judul", judul);
				Log.d("judul", lat);
				Log.d("judul", lon);
				 
				// Toast.makeText(getActivity(),
				// kul.getId_kuliner(), Toast.LENGTH_SHORT)
				// .show();

				// displayView(kul.getId_kuliner().toString());
				// judul = gridArray.get(position).getTitle();
				// Log.d("judul", judul);

			}

		});

	}

	private AlertDialog filter() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		String[] Option = { "Kuliner", "Oriental" };

		builder.setSingleChoiceItems(Option, 3,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// Toast.makeText(getActivity(), which + "selected",
						// Toast.LENGTH_LONG);
						switch (which) {
						case 0:
							tipe_url = 3;
							break;
						case 1:
							tipe_url = 4;
							break;
						default:
							break;
						}
						new GetKuliner().execute();
						dialog.dismiss();
						// Intent i = new Intent(getActivity(),
						// EventActivity.class);
						// judul = kul.getId_kuliner().toString();
						// i.putExtra("judul", judul);
						// startActivity(i);

						// Toast.makeText(getActivity().getApplicationContext(),
						// "this is my Toast message!!! =)",
						// Toast.LENGTH_LONG).show();
					}
				});

		return builder.create();
	}

	private AlertDialog sort() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		String[] Option = { "A - Z", "Z - A" };

		builder.setSingleChoiceItems(Option, 3,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// Toast.makeText(getActivity(), which + "selected",
						// Toast.LENGTH_LONG);
						switch (which) {
						case 0:
							tipe_url = 1;
							break;
						case 1:
							tipe_url = 2;
							break;
						default:
							break;
						}
						new GetKuliner().execute();
						dialog.dismiss();
						// Intent i = new Intent(getActivity(),
						// EventActivity.class);
						// judul = kul.getId_kuliner().toString();
						// i.putExtra("judul", judul);
						// startActivity(i);
//
//						Toast.makeText(getActivity().getApplicationContext(),
//								"this is my Toast message!!! =)",
//								Toast.LENGTH_LONG).show();
					}
				});

		return builder.create();
	}

	private void displayView(String id) {
		Fragment fragment = null;

		// fragment = new SubKulinerFragment(id);

		if (fragment != null) {
			FragmentManager fragManager = getFragmentManager();
			fragManager.beginTransaction()
					.replace(R.id.frame_container, fragment)
					.addToBackStack("BackSub2Frag").commit();

		} else {
			Log.e("Error", "Fragment SubMenu Error");
		}
	}

}
